/**
 * Created with IntelliJ IDEA.
 * User: yanshiyi
 * Date: 13-12-4
 * Time: 下午9:04
 * To change this template use File | Settings | File Templates.
 */
package expression

import (
	C "collections"
	"bytes"
	"strings"
	"fmt"
)

func TranslateInfix2postfix(expr string) string {

	var buffer bytes.Buffer
	stack := new(C.ArrayStack)

	for _, token := range strings.Split(expr, " ") {

		switch token {
			case "(": fallthrough
			case "*": fallthrough
			case "/": stack.Push(token)
					   fmt.Println(token, stack)
			case "+": fallthrough
			case "-":  pop(stack, &buffer)
					    stack.Push(token)
						fmt.Println(token, stack)
			case ")": fmt.Println(token, "left")
						popToLeft(stack, &buffer)
			default:  buffer.WriteString(token)
		}
	}

	for operator := stack.Pop(); operator != nil; operator = stack.Pop() {
		buffer.WriteString(operator.(string))
	}
	return buffer.String()
}

func popToLeft(stack C.Stack, buffer *bytes.Buffer) {

	for operator := stack.Pop(); operator != nil && operator != "("; operator = stack.Pop() {
		buffer.WriteString(operator.(string))
	}
}

func pop(stack C.Stack, buffer *bytes.Buffer) {

	for operator := stack.Pop(); operator != nil; operator = stack.Pop() {

		if operator == "(" {
			stack.Push(operator)
			return
		}

		switch operator {
			case "*": fallthrough
			case "/": buffer.WriteString(operator.(string))
			case "+": fallthrough
			case "-": stack.Push(operator)
						return
		}
	}
}
